package com.jrx.anytxn.param.service.partner.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.InternetUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.feign.common.GateWayPredicate;
import com.jrx.anytxn.feign.gateway.bean.AcctInfo;
import com.jrx.anytxn.feign.gateway.request.CoreRequest04;
import com.jrx.anytxn.feign.gateway.response.CoreResponse04;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.feign.transaction.request.GlInterfaceReq;
import com.jrx.anytxn.feign.transaction.service.IAnyTxnTransactionService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.dto.partner.PartnerLimitAdjustmentReq;
import com.jrx.anytxn.param.dto.partner.PartnerLimitAdjustmentRes;
import com.jrx.anytxn.param.dto.system.SystemParameterRes;
import com.jrx.anytxn.param.entity.*;
import com.jrx.anytxn.param.mapper.ext.*;
import com.jrx.anytxn.param.service.partner.IPartnerGeneralService;
import com.jrx.anytxn.param.service.partner.IPartnerShareProfitService;
import com.jrx.anytxn.param.service.partner.IPmPartnerInfoService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.service.system.ISequenceNumberService;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 合作方service实现
 *
 * @author : lbz
 * 2020/7/21
 */
@Service
public class PartnerGeneralServiceImpl implements IPartnerGeneralService {

    private static final Logger logger = LoggerFactory.getLogger(PartnerShareProfitServiceImpl.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IPmPartnerInfoService pmPartnerInfoService;
    @Autowired
    private IPartnerShareProfitService partnerShareProfitService;
    @Resource
    private ExtTlPartnerGeneralLogMapper extTlPartnerGeneralLogMapper;
    @Lazy
    @Autowired
    private IAnyTxnTransactionService anyTxnTransactionService;
    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtTlPartnerTransferLogMapper extTlPartnerTransferLogMapper;
    @Resource
    private ExtPrShareProfitTableMapper extPrShareProfitTableMapper;
    @Resource
    private ExtPrVerifyFileTableMapper extPrVerifyFileTableMapper;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;
    @Autowired
    private ISystemParameterService systemParameterService;
    @Resource
    private ExtPmPartnerInfoMapper extPmPartnerInfoMapper;
    @Autowired
    ISequenceNumberService sequenceNumberService;
    @Override
    public void shareProfit(PrProductTable prProductTable) throws Exception {
        PrOrganizationTable organization =
                organizationTableService.findByOrId(prProductTable.getOrganizationId(), prProductTable.getTenantId());
        Date toDay = organization.getToday();

        if(null == prProductTable.getPartnerId()){
            logger.info("产品：" + prProductTable.getPartnerId() + "未设置合作方编号，无需分润");
            return;
        }
        //获取合作方参数
        PmPartnerInfo pmPartnerInfo = pmPartnerInfoService.getByPartnerId(
                prProductTable.getTenantId(),prProductTable.getPartnerId());
        if(null == pmPartnerInfo || null == pmPartnerInfo.getProfitId()){
            logger.info("合作方未设置分润参数，无需分润");
            return;
        }

        PrShareProfitTable prShareProfitTable = partnerShareProfitService.getByShareProfitId(pmPartnerInfo.getTenantId(),pmPartnerInfo.getProfitId());
        //判断是否需要分润
        if(toDay.compareTo(prShareProfitTable.getNextShareDate()) != 0){
            logger.info("未到分润日期，无需分润");
            return;
        }
        TlPartnerGeneralLog tlPartnerGeneralLog;
        if(Constant.SHARE_UNIT_0.equals(prShareProfitTable.getShareUnit())){
            //按日分润
            tlPartnerGeneralLog = extTlPartnerGeneralLogMapper.sumShareAmountByProductId(prProductTable.getProductId(),prProductTable.getTenantId(),toDay);
        }else{
            //按周或月分润
            tlPartnerGeneralLog = extTlPartnerGeneralLogMapper.sumShareAmountByProIdAndBusiDate(
                    prProductTable.getProductId(),prProductTable.getTenantId(),
                    prShareProfitTable.getLastShareDate(),prShareProfitTable.getNextShareDate());
        }

        if(tlPartnerGeneralLog.getShareAmount().compareTo(BigDecimal.ZERO) == 0){
            logger.info("分润金额为0，无需分润");
            return;
        }

        //转账
        if(tlPartnerGeneralLog.getShareInterest().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getShareInterest(),prProductTable, organization,
                    Constant.TXN_CODE_INST_SHARE,"利息分润",Constant.TRANSFER_TYPE_1,pmPartnerInfo.getProfitAcct());
        }
        if(tlPartnerGeneralLog.getShareInstallmentFee().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getShareInstallmentFee(),prProductTable,
                    organization,Constant.TXN_CODE_INSTALLMENT_FEE_SHARE,"分期手续费分润",Constant.TRANSFER_TYPE_2,pmPartnerInfo.getProfitAcct());
        }
        if(tlPartnerGeneralLog.getSharePrepayFee().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getSharePrepayFee(),prProductTable,
                    organization,Constant.TXN_CODE_PREPAY_FEE_SHARE,"提前还款手续费分润",Constant.TRANSFER_TYPE_3,pmPartnerInfo.getProfitAcct());
        }
        if(tlPartnerGeneralLog.getSharePenalty().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getSharePenalty(),prProductTable,
                    organization,Constant.TXN_CODE_PENALTY_SHARE,"罚息分润",Constant.TRANSFER_TYPE_4,pmPartnerInfo.getProfitAcct());
        }
        if(tlPartnerGeneralLog.getShareCompound().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getShareCompound(),prProductTable,
                    organization,Constant.TXN_CODE_COMPOUND_SHARE,"复利分润",Constant.TRANSFER_TYPE_5,pmPartnerInfo.getProfitAcct());
        }
        if(tlPartnerGeneralLog.getSharePreoffFee().compareTo(BigDecimal.ZERO) > 0){
            transfer(tlPartnerGeneralLog.getSharePreoffFee(),prProductTable,
                    organization,Constant.TXN_CODE_PAYOFF_FEE_SHARE,"提前结清手续费分润",Constant.TRANSFER_TYPE_6,pmPartnerInfo.getProfitAcct());
        }
    }

    @Override
    public TlPartnerGeneralLog createTlPartnerGeneralLog(String message) throws Exception {
        TlPartnerGeneralLog log = new TlPartnerGeneralLog();
        String[] logs = message.split("\\|@\\|");
        try {
            log.setId(segmentService.getId(Constant.TL_PARTNER_GENERA_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        log.setTenantId(logs[0]);
        log.setOrganizationId(logs[1]);
        log.setProductId(logs[2]);
        Date busDate = DateUtils.parseDate(logs[3]);
        log.setBusinessDate(busDate);
        log.setLoanTotalCount(Integer.valueOf(logs[4]));
        log.setLoanTotalAmount(new BigDecimal(logs[5]));
        log.setCurrBalance(new BigDecimal(logs[6]));
        log.setPaymentCount(Integer.valueOf(logs[7]));
        log.setPaymentAmount(new BigDecimal(logs[8]));
        log.setPaymentPrincipal(new BigDecimal(logs[9]));
        log.setPaymentInterest(new BigDecimal(logs[10]));
        log.setPaymentInstallmentFee(new BigDecimal(logs[11]));
        log.setPaymentPrepayFee(new BigDecimal(logs[12]));
        log.setPaymentPenalty(new BigDecimal(logs[13]));
        log.setPaymentCompound(new BigDecimal(logs[14]));
        log.setPaymentPreoffFee(new BigDecimal(logs[15]));
        log.setShareAmount(new BigDecimal(logs[16]));
        log.setShareInterest(new BigDecimal(logs[17]));
        log.setShareInstallmentFee(new BigDecimal(logs[18]));
        log.setSharePrepayFee(new BigDecimal(logs[19]));
        log.setSharePenalty(new BigDecimal(logs[20]));
        log.setShareCompound(new BigDecimal(logs[21]));
        log.setSharePreoffFee(new BigDecimal(logs[22]));
        log.setUpdateBy(Constant.DEFAULT_USER);
        log.setRecordVersionNumber(Constant.VERSION_NUMBER);//初始版本号

        return log;
    }

    @Override
    public void updateshareProfit(List<PrShareProfitTable> tableList, PrOrganizationTable organization) {
        if(CollectionUtils.isEmpty(tableList)){
            return;
        }
        List<PrShareProfitTable> updateList = new ArrayList<>();
        for(PrShareProfitTable table : tableList){
            PrShareProfitTable updateTable = new PrShareProfitTable();
            updateTable.setShareProfitId(table.getShareProfitId());
            updateTable.setTenantId(table.getTenantId());
            updateTable.setLastShareDate(table.getNextShareDate());
            //计算下一分润日期
            if(Constant.SHARE_UNIT_0.equals(table.getShareUnit())){
                updateTable.setNextShareDate(organization.getNextProcessingDate());
            }else if(Constant.SHARE_UNIT_1.equals(table.getShareUnit())){
                Date nextDate = DateUtils.getDate(organization.getToday(),7);
                updateTable.setNextShareDate(nextDate);
            }else if(Constant.SHARE_UNIT_2.equals(table.getShareUnit())){
                Date nextDate = DateUtils.addMonth(organization.getToday(),1);
                updateTable.setNextShareDate(nextDate);
            }
            updateList.add(updateTable);
        }

        extPrShareProfitTableMapper.updateByBatch(updateList);
    }

    @Override
    public void createGeneralFile(PrProductTable table, String basePath,PrOrganizationTable org ,String today) throws IOException {
        //根据产品查询对账文件配置
        PrVerifyFileTable verifyFileTable = extPrVerifyFileTableMapper.selectByVerifyFileIdAndTenantId(table.getVerifyFileId(),table.getTenantId());
        if(null == verifyFileTable){
            return;
        }

        String filePath = basePath + org.getTenantId() + File.separator + today + File.separator + table.getProductId() + File.separator;

        //是否需要生成累计对账文件
        if(verifyFileTable.getVerifyFileType().contains(Constant.VERIFY_FILE_TYPE_01)){
            //没有数据也生成空文件
            createFolder(filePath,today,table.getProductId(),Constant.VERIFY_FILE_NAME_GENERAL_ALL);
            //生成文件数据
            TlPartnerGeneralLog log = extTlPartnerGeneralLogMapper.selectTotalByProductId(table.getProductId(),table.getTenantId());
            if(null != log){
                String fileMessage = createFileMessage(log,today);
                createFile(fileMessage,filePath,today,table.getProductId(),Constant.VERIFY_FILE_NAME_GENERAL_ALL);
            }
        }

        //是否需要生成当日对账文件
        if(verifyFileTable.getVerifyFileType().contains(Constant.VERIFY_FILE_TYPE_02)){
            //没有数据也生成空文件
            createFolder(filePath,today,table.getProductId(),Constant.VERIFY_FILE_NAME_GENERAL_TODAY);
            //生成文件数据
            TlPartnerGeneralLog log = extTlPartnerGeneralLogMapper.selectByProductIdAndBusiDate(
                    table.getProductId(),table.getTenantId(),org.getToday());
            if(null != log){
                String fileMessage = createFileMessage(log,today);
                createFile(fileMessage,filePath,today,table.getProductId(),Constant.VERIFY_FILE_NAME_GENERAL_TODAY);
            }
        }


    }

    @Override
    public void updatePartnerLimit(List<PmPartnerInfo> pmPartnerInfoList) {
        if(CollectionUtils.isEmpty(pmPartnerInfoList)){
            return;
        }
        List<PmPartnerInfo> updatelist = new ArrayList<>();
        for(PmPartnerInfo info: pmPartnerInfoList){
            PmPartnerInfo update = new PmPartnerInfo();
            update.setPartnerId(info.getPartnerId());
            update.setTenantId(info.getTenantId());
            //贷款总可用额度 大于 当日限额
            if(info.getAvailableLimit().compareTo(info.getDailyLimit()) > 0){
                update.setDailyAvailableLimit(info.getDailyLimit());
            }else{
                update.setDailyAvailableLimit(info.getAvailableLimit());
            }
            updatelist.add(update);
        }
        extPmPartnerInfoMapper.batchUpdatePmPartnerInfo(updatelist);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PartnerLimitAdjustmentRes partnerLimitAdjustment(PartnerLimitAdjustmentReq req){
        PartnerLimitAdjustmentRes res = new PartnerLimitAdjustmentRes();
        res.setSeqNo(req.getSeqNo());

        PmPartnerInfo pmPartnerInfo = extPmPartnerInfoMapper.selectByTenantIdAndPartnerId(req.getTenantId(),req.getPartnerId());
        PmPartnerInfo update = new PmPartnerInfo();
        update.setTenantId(pmPartnerInfo.getTenantId());
        update.setPartnerId(pmPartnerInfo.getPartnerId());

        //只有额度扣减才校验合作方额度
        if(Constant.ADJUSTMENT_TYPE_0.equals(req.getAdjustmentType())){
            if(req.getAmout().compareTo(pmPartnerInfo.getAvailableLimit()) > 0){
                logger.debug(TxnRespCode.LOAN_GT_FARTNER_AVAILABLE_LIMIT.getMsg());
                res.setSumStatus(Constant.ADJUSTMENT_STATUS_F);
                return res;
            }
            if(req.getAmout().compareTo(pmPartnerInfo.getDailyAvailableLimit()) > 0){
                logger.debug(TxnRespCode.LOAN_GT_FARTNER_DAILY_AVAILABLE_LIMIT.getMsg());
                res.setSumStatus(Constant.ADJUSTMENT_STATUS_F);
                return res;
            }
        }

        BigDecimal advLimit = BigDecimal.ZERO;
        BigDecimal dailyLimit = BigDecimal.ZERO;
        if(Constant.ADJUSTMENT_TYPE_0.equals(req.getAdjustmentType())){
            //额度扣减
            advLimit = pmPartnerInfo.getAvailableLimit().subtract(req.getAmout());//贷款总可用额度
            dailyLimit = pmPartnerInfo.getDailyAvailableLimit().subtract(req.getAmout());//当日可用额度
        }else if(Constant.ADJUSTMENT_TYPE_1.equals(req.getAdjustmentType())){
            //额度恢复
            advLimit = pmPartnerInfo.getAvailableLimit().add(req.getAmout());//贷款总可用额度
            dailyLimit = pmPartnerInfo.getDailyAvailableLimit().add(req.getAmout());//当日可用额度
            //当日可用额度不能超过 单日贷款限额
            if(dailyLimit.compareTo(pmPartnerInfo.getDailyLimit()) > 0 ){
                dailyLimit = pmPartnerInfo.getDailyLimit();
            }
        }
        update.setAvailableLimit(advLimit);
        update.setDailyAvailableLimit(dailyLimit);
        update.setUpdateBy(Constant.DEFAULT_USER);

        extPmPartnerInfoMapper.updateByTenantIdAndPartnerId(update);
        res.setSumStatus(Constant.ADJUSTMENT_STATUS_S);
        return res;
    }

    private TlPartnerTransferLog buildTransferLog(BigDecimal amount,PrProductTable productTable,
                                  PrOrganizationTable organization,String desc,String transferType) throws TxnBizException {
        TlPartnerTransferLog transferLog = new TlPartnerTransferLog();
        try {
            transferLog.setId(segmentService.getId(Constant.PR_PRODUCT_TABLE));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        transferLog.setTenantId(productTable.getTenantId());
        transferLog.setOrganizationId(productTable.getOrganizationId());
        transferLog.setProductId(productTable.getProductId());
        transferLog.setAmount(amount);
        transferLog.setSeqNo(Constant.TRANSFER_LOG_SEQ_PREFIX + SeqUtils.getSNByLength(Constant.TRANSFER_LOG_SEQ_RADOM_LENGTH));//流水号	唯一索引 PL+yyyyMMddHHmmssSSS +13位随机
        transferLog.setBusinessDate(organization.getNextProcessingDate());
        transferLog.setTransferType(transferType);
        transferLog.setNarrative(desc);
        transferLog.setRefNo(sequenceNumberService.generateRefNo(Constant.SEQUENCE_LENGTH));
        transferLog.setSumStatus(Constant.TRANSFER_SUM_STATUS_D);
        transferLog.setLaunchTime(DateUtils.getBusinessTime(new Date(), organization.getNextProcessingDate()));
        transferLog.setUpdateBy(Constant.DEFAULT_USER);
        transferLog.setRecordVersionNumber(Constant.VERSION_NUMBER);

        extTlPartnerTransferLogMapper.insertSelective(transferLog);
        return transferLog;
    }

    private void transfer(BigDecimal amount,PrProductTable productTable,
                          PrOrganizationTable organization,String txnCode,String desc,String transferType,String profitAcct) throws Exception {
        TlPartnerTransferLog log = buildTransferLog(amount,productTable,organization,desc,transferType);

        String coreRequest04Json  = buildCoreRequest04Json(amount,productTable,profitAcct);
        //调用网关转账接口
        GateWayPredicate<CoreResponse04> collectionPre = () -> innerGatewayService.transferAcct(coreRequest04Json);
        CoreResponse04 res = null;
        try {
            res = collectionPre.getRes(collectionPre);
        }catch (Exception e){
            logger.error("调用转账接口出现异常",e);
        }

        TlPartnerTransferLog updateLog = new TlPartnerTransferLog();
        updateLog.setId(log.getId());
        updateLog.setProductId(log.getProductId());
        updateLog.setTenantId(log.getTenantId());
        if(res == null ) {
            updateLog.setSumStatus(Constant.TRANSFER_SUM_STATUS_F);
            updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), organization.getNextProcessingDate()));
        }else{
            String result = res.getDealResult();
            updateLog.setReturnCode(res.getBusCode());
            updateLog.setReturnMessage(res.getBusMsg());
            updateLog.setReturnStatus(result);
            updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), organization.getNextProcessingDate()));
            if (Constant.GATEWAY_DEAL_SUC.equals(result)) { //成功
                updateLog.setSumStatus(Constant.TRANSFER_SUM_STATUS_S);
            } else if (Constant.GATEWAY_DEAL_FAIL.equals(result)) {//失败
                updateLog.setSumStatus(Constant.TRANSFER_SUM_STATUS_F);
            }
        }
        extTlPartnerTransferLogMapper.updateByTenIdAndProductId(updateLog);

        //记录GL流水
        GlInterfaceReq req = new GlInterfaceReq();
        req.setTenantId(productTable.getTenantId());
        req.setOrganizationId(productTable.getOrganizationId());
        req.setLoanProductId(productTable.getProductId());
        req.setAmount(amount);
        req.setGlDate(organization.getNextProcessingDate());
        req.setTxnCode(txnCode);
        //记录GL流水
        anyTxnTransactionService.buildTlGlInterfaceInfo(req);
    }

    private String buildCoreRequest04Json(BigDecimal amount,PrProductTable productTable,String profitAcct) throws Exception {
        CoreRequest04 req = new CoreRequest04();
        req.setServiceId(Constant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(productTable.getTenantId());
        req.setServiceSeq(Constant.TRANSFER_LOG_SEQ_PREFIX+ SeqUtils.getSNByLength(Constant.TRANSFER_LOG_SEQ_RADOM_LENGTH));
        req.setCcy(Constant.CURRENCY_CNY);

        List<AcctInfo> acctList = new ArrayList<>();

        AcctInfo inerAcctinfo = new AcctInfo();
        SystemParameterRes bankCardRes = systemParameterService.findByParamCode(Constant.INNER_BANK_CARD
                ,productTable.getTenantId());
        inerAcctinfo.setAcctNo(bankCardRes.getParamValue());
        inerAcctinfo.setCdFlag("D");
        inerAcctinfo.setTranAmnt(amount.toString());
        inerAcctinfo.setDesc(null);
        inerAcctinfo.setFreezeNo(null);
        acctList.add(inerAcctinfo);

        AcctInfo profit = new AcctInfo();
        inerAcctinfo.setAcctNo(profitAcct);
        inerAcctinfo.setCdFlag("C");
        inerAcctinfo.setTranAmnt(amount.toString());
        inerAcctinfo.setDesc(null);
        inerAcctinfo.setFreezeNo(null);
        acctList.add(profit);

        req.setAcctList(acctList);
        String coreRequest04 = JsonUtils.toJSon(req);
        return coreRequest04;
    }


    private String createFileMessage(TlPartnerGeneralLog log,String today){
        StringBuffer sb = new StringBuffer();
        sb.append(today + Constant.separator);
        sb.append(log.getLoanTotalCount() + Constant.separator);
        sb.append(log.getLoanTotalAmount() + Constant.separator);
        sb.append(log.getPaymentCount() + Constant.separator);
        sb.append(log.getPaymentAmount() + Constant.separator);
        sb.append(log.getPaymentPrincipal() + Constant.separator);
        sb.append(log.getPaymentInterest() + Constant.separator);
        sb.append(log.getPaymentInstallmentFee()+ Constant.separator);
        sb.append(log.getPaymentPrepayFee()+ Constant.separator);
        sb.append(log.getPaymentPenalty()+ Constant.separator);
        sb.append(log.getPaymentCompound()+ Constant.separator);
        sb.append(log.getPaymentPreoffFee()+ Constant.separator);
        sb.append(log.getShareAmount()+ Constant.separator);
        sb.append(log.getShareInterest()+ Constant.separator);
        sb.append(log.getShareInstallmentFee()+ Constant.separator);
        sb.append(log.getSharePrepayFee()+ Constant.separator);
        sb.append(log.getSharePenalty()+ Constant.separator);
        sb.append(log.getShareCompound()+ Constant.separator);
        sb.append(log.getSharePreoffFee());

        return sb.toString();
    }


    private void createFolder(String basePath,String today,String productId,String fileType){
        String fileName = productId + "_" + today +"_" + fileType + ".txt";

        Path verifyFile = Paths.get(basePath + fileName);
        Path pFile = Paths.get(basePath);

        if (!Files.exists(verifyFile)) {
            //判断文件夹是否存在
            if (!Files.isDirectory(pFile)) {
                try {
                    Files.createDirectories(pFile);
                } catch (IOException e) {
                    logger.error("创建目录失败",e);
                }
            }
            //创建文件
            try {
                Files.createFile(verifyFile);
            } catch (IOException e) {
                logger.error("创建文件失败",e);
            }
        }
    }


    private void createFile(String fileMessage,String basePath,String today,String productId,String fileType){
        String fileName = productId + "_" + today +"_" + fileType + ".txt";

        File file = new File(basePath + fileName);

        try (FileWriter fw = new FileWriter(file);
             BufferedWriter writer = new BufferedWriter(fw) ){
            writer.write(fileMessage);
            writer.flush();
        } catch (IOException e) {
            logger.error("生成文件失败");
            throw new RuntimeException(e);
        }
    }
}
